package com.sogou.nebula.pms.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.log4j.Logger;

/**
 * @author taoming 2012-7-5下午03:33:49
 */
public class HttpRequestProxyUtils {

    // 连接超时
    private static int    connectTimeOut  = 5000;

    // 读取数据超时
    private static int    readTimeOut     = 10000;

    // 请求编码
    private static String requestEncoding = "GBK";

    // 日志请求
    private static Logger logger          = Logger.getLogger(HttpRequestProxyUtils.class);

    /**
     * 发送带参数的GET的HTTP请求
     * 
     * @author taoming
     * @param reqUrl HTTP请求URL
     * @param parameters 参数映射表
     * @param recvEncoding 接收编码
     * @return HTTP响应的字符串
     */
    public static String doGet(String reqUrl, Map parameters, String recvEncoding) {

        HttpURLConnection httpURLConnection = null;
        String responseContent = null;
        try {
            StringBuffer params = new StringBuffer();
            // 构建get方式的请求url参数
            for (Iterator iter = parameters.entrySet().iterator(); iter.hasNext();) {
                Entry element = (Entry) iter.next();
                params.append(element.getKey().toString());
                params.append("=");
                params.append(URLEncoder.encode(element.getValue().toString(), recvEncoding));
                params.append("&");
            }
            // 删除最后一个和&
            if (params.length() > 0) {
                params = params.deleteCharAt(params.length() - 1);
            }
            URL url = new URL(reqUrl);
            httpURLConnection = (HttpURLConnection) url.openConnection();

            httpURLConnection.setRequestMethod("GET");
            // 连接超时（单位：毫秒）
            httpURLConnection.setConnectTimeout(5000);
            // 读操作超时（单位：毫秒）
            httpURLConnection.setReadTimeout(5000);

            httpURLConnection.setDoOutput(true);
            byte[] b = params.toString().getBytes();
            httpURLConnection.getOutputStream().write(b, 0, b.length);
            httpURLConnection.getOutputStream().flush();
            httpURLConnection.getOutputStream().close();

            InputStream in = httpURLConnection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(in, recvEncoding));
            String tempLine = rd.readLine();
            StringBuffer temp = new StringBuffer();
            String crlf = System.getProperty("line.separator");
            while (tempLine != null) {
                temp.append(tempLine);
                temp.append(crlf);
                tempLine = rd.readLine();
            }
            responseContent = temp.toString();
            rd.close();
            in.close();
        } catch (IOException e) {
            logger.error("网络故障", e);
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }
        return responseContent;
    }

    /**
     * 发送不带参数的GET的HTTP请求
     * 
     * @author taoming
     * @param reqUrl HTTP请求URL
     * @param recvEncoding 接收编码
     * @return HTTP响应的字符串
     */
    public static String doGet(String reqUrl, String recvEncoding) {
        HttpURLConnection httpURLConnection = null;
        String responseContent = null;
        try {
            StringBuffer params = new StringBuffer();
            String queryUrl = reqUrl;
            int paramIndex = reqUrl.indexOf("?");

            if (paramIndex > 0) {
                queryUrl = reqUrl.substring(0, paramIndex);
                String parameters = reqUrl.substring(paramIndex + 1, reqUrl.length());
                String[] paramArray = parameters.split("&");
                for (int i = 0; i < paramArray.length; i++) {
                    String string = paramArray[i];
                    int index = string.indexOf("=");
                    if (index > 0) {
                        String parameter = string.substring(0, index);
                        String value = string.substring(index + 1, string.length());
                        params.append(parameter);
                        params.append("=");
                        params.append(URLEncoder.encode(value, HttpRequestProxyUtils.requestEncoding));
                        params.append("&");
                    }
                }
                params = params.deleteCharAt(params.length() - 1);
            }

            URL url = new URL(queryUrl);
            httpURLConnection = (HttpURLConnection) url.openConnection();

            httpURLConnection.setRequestMethod("GET");
            // 连接超时（单位：毫秒）
            httpURLConnection.setConnectTimeout(5000);
            // 读操作超时（单位：毫秒）
            httpURLConnection.setReadTimeout(5000);

            byte[] b = params.toString().getBytes();
            httpURLConnection.getOutputStream().write(b, 0, b.length);
            httpURLConnection.getOutputStream().flush();
            httpURLConnection.getOutputStream().close();
            InputStream in = httpURLConnection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(in, recvEncoding));
            String tempLine = rd.readLine();
            StringBuffer temp = new StringBuffer();
            String crlf = System.getProperty("line.separator");
            while (tempLine != null) {
                temp.append(tempLine);
                temp.append(crlf);
                tempLine = rd.readLine();
            }
            responseContent = temp.toString();
            rd.close();
            in.close();
        } catch (IOException e) {
            logger.error("网络故障", e);
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }
        return responseContent;
    }

    /**
     * 发送带参数的POST的HTTP请求
     * 
     * @author taoming
     * @param reqUrl HTTP请求URL
     * @param parameters 参数映射表
     * @param recvEncoding 接收编码
     * @return HTTP响应的字符串
     */
    public static String doPost(String reqUrl, Map parameters, String recvEncoding) {
        HttpURLConnection httpURLConnection = null;
        String responseContent = null;
        try {
            StringBuffer params = new StringBuffer();
            for (Iterator iter = parameters.entrySet().iterator(); iter.hasNext();) {
                Entry element = (Entry) iter.next();
                params.append(element.getKey().toString());
                params.append("=");
                params.append(URLEncoder.encode(element.getValue().toString(), recvEncoding));
                params.append("&");
            }

            if (params.length() > 0) {
                params = params.deleteCharAt(params.length() - 1);
            }
            System.out.println(reqUrl);
            URL url = new URL(reqUrl);
            httpURLConnection = (HttpURLConnection) url.openConnection();

            httpURLConnection.setRequestMethod("POST");
            // 连接超时（单位：毫秒）
            httpURLConnection.setConnectTimeout(50000);
            // 读操作超时（单位：毫秒）
            httpURLConnection.setReadTimeout(500000);
            httpURLConnection.setDoOutput(true);
            byte[] b = params.toString().getBytes();
            httpURLConnection.getOutputStream().write(b, 0, b.length);
            httpURLConnection.getOutputStream().flush();
            httpURLConnection.getOutputStream().close();

            InputStream in = httpURLConnection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(in, recvEncoding));
            String tempLine = rd.readLine();
            StringBuffer tempStr = new StringBuffer();
            String crlf = System.getProperty("line.separator");
            while (tempLine != null) {
                tempStr.append(tempLine);
                tempStr.append(crlf);
                tempLine = rd.readLine();
            }
            responseContent = tempStr.toString();
            rd.close();
            in.close();
        } catch (IOException e) {
            logger.error("网络故障", e);
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }
        return responseContent;
    }

    /**
     * 该方法用来构建URL对象，获取返回数据。
     * 
     * @author taoming
     * @param urlStr
     * @return
     * @throws Exception
     */
    public String getResponseDataByURL(String urlStr) throws Exception {
        URL url = new URL(urlStr);
        InputStream in = url.openStream();
        int count = 0;
        while (count == 0) {
            count = in.available();
        }
        byte[] b = new byte[count];
        in.read(b);
        String sid = new String(b, "UTF-8");
        return sid;
    }

    /**
     * @return 连接超时(毫秒)
     * @see com.HttpRequestProxyUtils.common.web.HttpRequestProxy#connectTimeOut
     */
    public static int getConnectTimeOut() {
        return HttpRequestProxyUtils.connectTimeOut;
    }

    /**
     * @return 读取数据超时(毫秒)
     * @see com.HttpRequestProxyUtils.common.web.HttpRequestProxy#readTimeOut
     */
    public static int getReadTimeOut() {
        return HttpRequestProxyUtils.readTimeOut;
    }

    /**
     * @return 请求编码
     * @see com.HttpRequestProxyUtils.common.web.HttpRequestProxy#requestEncoding
     */
    public static String getRequestEncoding() {
        return requestEncoding;
    }

    /**
     * @param connectTimeOut 连接超时(毫秒)
     * @see com.HttpRequestProxyUtils.common.web.HttpRequestProxy#connectTimeOut
     */
    public static void setConnectTimeOut(int connectTimeOut) {
        HttpRequestProxyUtils.connectTimeOut = connectTimeOut;
    }

    /**
     * @param readTimeOut 读取数据超时(毫秒)
     * @see com.HttpRequestProxyUtils.common.web.HttpRequestProxy#readTimeOut
     */
    public static void setReadTimeOut(int readTimeOut) {
        HttpRequestProxyUtils.readTimeOut = readTimeOut;
    }

    /**
     * @param requestEncoding 请求编码
     * @see com.HttpRequestProxyUtils.common.web.HttpRequestProxy#requestEncoding
     */
    public static void setRequestEncoding(String requestEncoding) {
        HttpRequestProxyUtils.requestEncoding = requestEncoding;
    }

    public static void main(String[] args) {
        Map parameters = new HashMap();
        parameters.put("uid", "bizpms@sogou-inc.com");
        parameters.put("fr_name", "项目管理系统1111");
        parameters.put("fr_addr", "bizpms@sogou-inc.com");
        parameters.put("title", "test");
        parameters.put("body", "testsdftebody");
        parameters.put("mode", "html");
        parameters.put("attname", "");
        parameters.put("attbody", "");
        String tempMailTo = "taoming@sogou-inc.com;taoming@sogou-inc.com";
        parameters.put("maillist", tempMailTo);
        String temp = HttpRequestProxyUtils.doPost("http://portal.sys.sogou-op.org/portal/tools/send_mail.php",
                                                   parameters, "utf-8");
        System.out.println("返回的消息是:" + temp);
    }
}
